/*
 * @Author: gk 
 *  用户管理
 * @Date: 2018-03-15 14:44:57 
 * @Last Modified by: csy
 * @Last Modified time: 2019-06-12 15:58:11
 */
layui.config({}).use(['element', 'zlConfig', 'zlContext', 'table', 'layer', 'form'], function (exports) {
	var $ = layui.$,
		zlContext = layui.zlContext,
		layer = layui.layer,
		table = layui.table,
		form = layui.form,
		zlConfig = layui.zlConfig,
		statusName = zlConfig.global.result.statusName,
		msgName = zlConfig.global.result.msgName,
		dataName = zlConfig.global.result.dataName,
        OK = zlConfig.global.result.okState,
        curUserVo = zlContext.getCurrentUser(),
        gFrReportIframe,
        zlReportArgments = {},
        fullheight = 'full-40';
        
	var tableObj, fromlayerIndex, frIframeReloadIndex;
	//渲染用户列表
	tableObj = table.render({
		elem: '#tbOrgReprot',
		height: fullheight,
		response: zlConfig.global.gridResponse,
		limit: 999,
        page: false,
        where: {
            "ORGID": curUserVo["currentOrgId"]
        },
		url: layui.cache['contentPath'] + "/manager/coreauditreport/reportlist",
		method: 'post',
		sortload: true,
		cols: [
			[ //表头
				{
					type: 'numbers',
					fixed: 'left',
					title: '#'
				}, {
					field: 'OBJNAME',
                    title: '报表名称',
                    width: '45%',
					sort: true
				}, {
					field: 'JIZR',
                    title: '基准日',
                    width: '25%',
					sort: true
				}, {
					field: 'SYS_AUDFLAG',
					title: '流程状态',
					unresize: true,
					templet: function (d) {
                        if("0" == d.SYS_AUDFLAG){
                            return "待处理";
                        }else if("1" == d.SYS_AUDFLAG){
                            return "已提交";
                        }else if("2" == d.SYS_AUDFLAG){
                            return "审核通过";
                        }else if("3" == d.SYS_AUDFLAG){
                            return "退回";
                        }else {
                            return "错误状态";
                        }
					}
				}, {
					fixed: 'right',
					width: 180,
					title: '操作',
					align: 'center',
					toolbar: '#barOrgReport'
				}
			]
		],
		event: {
			onRowdbClick: function (field, row) {
				gridAction.editRow(row);
			}
		}
	});

	var gridAction = {
		currentEditObj: undefined,
		orgReportGridedit: function (row, type, readonly) {
			var frm = [
                '<div class="layui-fluid">',
                '    <div class="layui-row  layui-col-space5">',
                '       <div class="layui-col-md12 docking-fill">',
                '           <div class="layui-card">',
                '               <div class="layui-card-body">',
                '                   <div class="zl-toolbar layui-hide">',
                '                       <button id="btnReportInitData" class="layui-btn layui-btn-sm' + (readonly == 'readonly' ? ' layui-hide' : '') + '">',
                '                          <i class="layui-icon layui-icon-table"></i>提取数据</button>',
                '                       <button id="btnReportSave" class="layui-btn layui-btn-sm' + (readonly == 'readonly' ? ' layui-hide' : '') + '">',
                '                           <i class="layui-icon layui-icon-form"></i>保存</button>',
                '                       <button id="btnReportAddRow" class="layui-btn layui-btn-sm' + (readonly == 'readonly' ? ' layui-hide' : '') + '">',
                '                           <i class="layui-icon layui-icon-add-circle-fine"></i>新增</button>',
                '                       <button id="btnReportDeleteRow" class="layui-btn layui-btn-sm' + (readonly == 'readonly' ? ' layui-hide' : '') + '">',
                '                           <i class="layui-icon layui-icon-delete"></i>删除</button>',
                '                       <button id="btnReportPrint" class="layui-btn layui-btn-sm">',
                '                            <i class="layui-icon layui-icon-print"></i>打印</button>',
                '                       <button id="btnReportExport" class="layui-btn layui-btn-sm">',
                '                              <i class="layui-icon layui-icon-print"></i>导出</button>',
                '                       <button id="btnReportSubmit" class="layui-btn layui-btn-sm' + (readonly == 'readonly' ? ' layui-hide' : '') + '">',
                '                           <i class="layui-icon layui-icon-form"></i>提交</button>',
                '                       <button id="btnShowProcessLog" class="layui-btn layui-btn-sm">',
                '                           <i class="layui-icon layui-icon-form"></i>查看流程状态</button>',
                '                   </div>',
                '                   <div class="zl-container">',
                '                       <div id="zl-reportFrame-container" class="zl-container">',
                '                           <form id="frm-reportFrame" action="" target="target-reportFrame" method="post">',
                '                               <input type="hidden" name="USERID" />',
                '                               <input type="hidden" name="ORGID" />',
                '                               <input type="hidden" name="DEPTID" />',
                '                               <input type="hidden" name="ROLEID" />',
                '                               <input type="hidden" name="ROLECODE" />',
                '                               <input type="hidden" name="RPT_ID" />',
                '                           </form>',
                '                           <iframe id="reportFrame" name="target-reportFrame" width =100% height =100%></iframe>',
                '                       </div>',
                '                   </div>',
                '               </div>',
                '           </div>',
                '       </div>',
                '   </div>',
                '</div>'
            ];
			layer.open({
				type: 1,
				limit: 999,
				title: "机构填报",
				id: 'coreOrgReportLayer',
				area: ['100%', '100%'],
				content: frm.join(''),
				success: function (layero, index) {
                    fromlayerIndex = index;
                    setMaxHeihgt(10,30);
                    //加载帆软报表
                   gridAction.onBeforeLoadFrReportIframe();
                   gridAction.onLoadFrReportIframe(row,type,readonly);

                    //头部按钮监听事件
                    $("#coreOrgReportLayer").on("click", "#btnReportInitData", function(){
                        reportAction.initReport();
                    });
                    $("#coreOrgReportLayer").on("click", "#btnReportSave", function(){
                        reportAction.saveCurReport();
                    });
                    $("#coreOrgReportLayer").on("click", "#btnReportAddRow", function(){
                        reportAction.addReport();
                    });
                    $("#coreOrgReportLayer").on("click", "#btnReportDeleteRow", function(args){
                        reportAction.deleteReport();
                    });
                    $("#coreOrgReportLayer").on("click", "#btnReportPrint",function(){
                        reportAction.printReport();
                    });
                    $("#coreOrgReportLayer").on("click", "#btnReportExport",function(){
                        reportAction.exportReport();
                    });
                    $("#coreOrgReportLayer").on("click", "#btnReportSubmit",function(){
                        reportAction.submitReport(row);
                    });
                    $("#coreOrgReportLayer").on("click", "#btnShowProcessLog",function(){
                        reportAction.showProcessLog();
                    });
				}
			});
		},
		editRow: function (row) {
            if(row["REPORT_ID"] && row["report"] && row.report["REP_LUJ"]){
                if(1 == row.SYS_AUDFLAG || 2 == row.SYS_AUDFLAG){
                    gridAction.orgReportGridedit(row, 'view', "readonly");
                }else{
                    gridAction.orgReportGridedit(row, 'write');
                }
            }else{
                zlContext.errorMsg("无法获取报表模板");
            }
        },
        onBeforeLoadFrReportIframe: function(){
            //加载帆软报表前调用：主要用于设置请求参数等
            $('#frm-reportFrame input[name="USERID"]').val(curUserVo["id"]);
            $('#frm-reportFrame input[name="ORGID"]').val(curUserVo["currentOrgId"]);
            $('#frm-reportFrame input[name="DEPTID"]').val(curUserVo["currentDeptId"]);
            $('#frm-reportFrame input[name="ROLEID"]').val(curUserVo["currentRoleId"]);
            $('#frm-reportFrame input[name="ROLECODE"]').val(curUserVo["currentRoleCode"]);
            $('#frm-reportFrame input[name="RPT_ID"]').val(gridAction.currentEditObj.data["RWID"]);
        },
        onLoadFrReportIframe: function(rptReport, type, readonly){
            //修改请求URL加载帆软报表
            var frUrl = rptReport.report["REP_LUJ"];
            if("write" == type){
                frUrl = frUrl.replace("op=view","op=write");
            }else{
                frUrl = frUrl.replace("op=write","op=view");
            }
            frIframeReloadIndex = layer.msg('数据查询中，请稍候...', {icon: 16, time: false,shade: 0.1 });
            //表单提交加载报表
            // frUrl = "/kdayun-report-fr/ReportServer?reportlet=ChongmHecbb%281%29.cpt&op=write&ORGID=556DE48F60000001FE767BA266C5EC11&RPT_ID=4BB6DA8D342747E2BD4B7F6B6579D281"
            $("#frm-reportFrame").attr("action",frUrl);
            $("#frm-reportFrame").submit();
            //设置报表回调
            gFrReportIframe = document.getElementById('reportFrame');
            gFrReportIframe.onload = gFrReportIframe.onreadystatechange = gridAction.onAfterLoadFrReportIframe;
        },
        onAfterLoadFrReportIframe: function(){
            //显示按钮
            $("#coreOrgReportLayer .zl-toolbar").removeClass("layui-hide");
            //加载完帆软报表后回调：用于关闭遮罩等
            layer.close(frIframeReloadIndex);
		},
		search: function () {
			layui.event('WM_USERDEF',
				zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, null);
		}
    }
    
    var reportAction = {
        saveCurReport: function(args){
            gFrReportIframe.contentWindow.contentPane.verifyAndWriteReport();
        },
        initReport: function(args){
            var row = gridAction.currentEditObj.data;
            var iframeDoc = document.getElementById('reportFrame').contentWindow.document;
            var $ifameDoc = $(iframeDoc);
            var sheetIndex = $ifameDoc.find(".fr-sheetbutton-container").index($ifameDoc.find(".fr-sheetbutton-container-active"));
            var params = {
                "RWID":row["RWID"],
                "sheetIndex":sheetIndex
            }
            params = $.extend(params, zlReportArgments);
            zlContext.confirm('询问', '是否确认提取报表数据?', function (index) {
                zlContext.post(layui.cache['contentPath'] + '/manager/coreauditreport/initreportdata', params, function (result) {
                    if (result[statusName] == OK) {
                        zlContext.successMsg('提数成功');
                        gFrReportIframe.contentWindow.contentPane.refreshAllSheets();
                        return true;
                    }
                    else {
                        zlContext.errorMsg(result[msgName]);
                    }
                });
                layer.close(index);
            });
        },
        addReport: function (args) {
            var iframeDoc = document.getElementById('reportFrame').contentWindow.document;
            var currentTd = gFrReportIframe.contentWindow.contentPane.curLGP.currentTDCell;
            if($(currentTd).children('div.ui-state-enabled').length > 0){
                //当前为可扩展单元格
                gFrReportIframe.contentWindow.contentPane.appendReportRC(1);
                return;
            }
            //单元单元格不可扩展
            var $ifameDoc = $(iframeDoc);
            var widgetArr = $ifameDoc.find('.x-table td[col=1]:visible');
            var i = widgetArr.length - 1;
            var td = undefined;
            for(;i >= 0;i--){
                td = widgetArr[i];
                var widget = $(td).children('div.ui-state-enabled');
                if(widget.length > 0){
                    break;
                }
                widget = undefined;
            }
			gFrReportIframe.contentWindow.contentPane.appendReportRC(1,$(td).attr('id'));
        },
        deleteReport: function (args) {
			gFrReportIframe.contentWindow.contentPane.deleteReportRC();
        },
        submitReport: function(){
            var row = gridAction.currentEditObj.data;
            var params = {
                "RWID":row["RWID"]
            }
            zlContext.confirm('询问', '是否要确定提交报表送审?', function (index) {
                zlContext.post(layui.cache['contentPath'] + '/manager/coreauditreport/orgsubmit', params, function (result) {
					if (result[statusName] == OK) {
                        zlContext.successMsg('提交成功');
                        gridAction.currentEditObj.update(result[dataName]);
                        $.extend(gridAction.currentEditObj.data,result[dataName]);
                        //隐藏相应按钮
                        $("#coreOrgReportLayer #btnReportInitData").addClass("layui-hide");
                        $("#coreOrgReportLayer #btnReportSave").addClass("layui-hide");
                        $("#coreOrgReportLayer #btnReportAddRow").addClass("layui-hide");
                        $("#coreOrgReportLayer #btnReportDeleteRow").addClass("layui-hide");
                        $("#coreOrgReportLayer #btnReportSubmit").addClass("layui-hide");
                        var retdata = result[dataName];
                        var reportUrl = retdata.report["REP_LUJ"];
                        reportUrl = reportUrl.replace("op=write","op=view");
                        //加载帆软报表
                        frIframeReloadIndex = layer.msg('报表加载中，请稍候...', {icon: 16, time: false,shade: 0.1 });
                        $("#frm-reportFrame").attr("action",reportUrl);
                        $("#frm-reportFrame").submit();
                        //设置报表回调
                        gFrReportIframe = document.getElementById('reportFrame');
                        gFrReportIframe.onload = gFrReportIframe.onreadystatechange = gridAction.onAfterLoadFrReportIframe;
						return true;
					}
					else {
						zlContext.errorMsg(result[msgName]);
					}
				});
                layer.close(index);
            });
        },
        showProcessLog: function(){
            var row = gridAction.currentEditObj.data;
            if(!row.SYS_AUDFLAG || row.SYS_AUDFLAG == 0 || !row.SYS_PID){
                zlContext.warnMsg('流程未启动');
                return;
            }
            var params = {
                "SYS_PID": row["SYS_PID"]
            }
            zlContext.post(layui.cache['contentPath'] + '/manager/coreauditreport/query/processlog', params, function (data) {
                var html = [
                            '<div class="layui-row">', 
                            '	<div class="layui-col-md12 docking-fill"><div class="layui-card-body">', 
                            '		<table id="tbFindWorkflow" class="layui-hide" lay-filter="tbWorkflow"></table>', 
                            '	</div></div>', 
                            '</div>'
                            ]
                layer.open({
                    type: 1,
                    title: '查看流程',
                    id: 'checkProcessLayer',
                    area: ['100%', '100%'],
                    content: html.join(''),
                    response: zlConfig.global.gridResponse,
                    success: function (layero, index) {
                        table.render({
                            elem: '#tbFindWorkflow',
                            height: 'full-65',
                            page: false,
                            sortload: false,
                            cols: [
                                [ //表头
                                    {
                                        type: 'numbers',
                                        fixed: 'left',
                                        title: '#'
                                    }, {
                                        field: 'NAME_ROLE',
                                        title: '审核人',
                                        width: '40%',
                                        sort: true
                                    }, {
                                        field: 'ORG_NAME',
                                        title: '机构名称',
                                        width: 300,
                                        sort: true
                                    }, {
                                        field: 'SYS_CREATETIME',
                                        title: '审核时间',
                                        width: 200,
                                        sort: true
                                    }, {
                                        field: 'USER_OPERATE',
                                        title: '操作',
                                        width: 200,
                                        sort: true
                                    }, {
                                        field: 'MESSAGE',
                                        title: '审核意见',
                                        sort: true
                                    }
                                ]
                            ],
                            data: data.obj,
                        });
                    }
                });
            });
        },
        printReport: function(args){
            gFrReportIframe.contentWindow.contentPane.noClientPrint();
        },
        exportReport: function(args){
            
        },
        writeState: function(state){
        }
    }

    //全局函数，报表保存成功的回调
    window.zlFrReportWriteSuccess = function(state){
		reportAction.writeState(state);
    }
    //全局函数，报表加载时用于设置请求参数
    window.setZlReportArgments = function(args){
        if(args){
            zlReportArgments = $.extend(zlReportArgments, args);
        }
    }
    //全局函数：获取报表对象
    window.getZlReport = function(){
        return gridAction.currentEditObj.data;
    }

	//监听行工具事件
	table.on('tool(tbOrgReprot)', function (obj) {
		var row = obj.data, //获得当前行数据
            layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            
		if (layEvent === 'edit-report') { //填报按钮
			gridAction.currentEditObj = obj;
			gridAction.editRow(row);
		}
    });
    
	//监听刷新的事件
	layui.event('WM_USERDEF', zlConfig.global.WM_USERDEF.REFRESHDATA_DATA, null, function (node) {
		var index = layer.msg('数据查询中，请稍候', {
			icon: 16,
			time: false,
			shade: 0.1
		});
		var loadGridData = function (id, url, param) {
			tableObj.reload({
				url: url,
				method: 'post',
				where: param,
				done: function (res, curr, count) {
					layer.close(index);
				}
			}, true);
		}
		var params = {
            "ORGID": curUserVo['currentOrgId']
        };
		
		loadGridData('tbOrgReprot', layui.cache['contentPath'] + '/manager/coreauditreport/reportlist', params);
    });
    
    //iframe自适应 控制高度的设置
	function setMaxHeihgt(deff, deff1) {
		$('.docking-left').height($(window).height() - deff);
		$('.docking-fill').height($(window).height() - deff);
		var treeHeaderH = $('.zltree-header').height();
        $('.layui-card-body').height($(window).height() - deff1);
        $('#coreOrgReportLayer .docking-fill').height($("#coreOrgReportLayer").height() - deff);
        $('#coreOrgReportLayer .layui-card-body').height($('#coreOrgReportLayer .docking-fill').height() - deff1);
        $("#coreOrgReportLayer .zl-container ").height($('#coreOrgReportLayer .layui-card-body').height() - deff1);
		$('.zltree-body').height($('.layui-card-body').height() - treeHeaderH - 20);
	}
	$(window).on('resize', function () {
		//控制高度的设置
		setMaxHeihgt(10,30);
    }).resize();
});